import { getCartList, updetaCart, delCart } from '@/apis/cart'

export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  mutations: {
    setCartList (state, newList) {
      state.cartList = newList
    },
    setCart (state, { obj, newNum }) {
      obj.goods_num = newNum
    },
    changeIsShow (state, flag) {
      state.cartList.forEach(item => { item.isChecked = flag })
    },
    // 选择框取反
    toggleCheck (state, id) {
      const obj = state.cartList.find(item => item.id === id)
      obj.isChecked = !obj.isChecked
    },
    // 全选反选模块
    // 让大选控制小选
    setSelect (state, boolSelect) {
      state.cartList.forEach(item => {
        item.isChecked = boolSelect
      })
    }
  },
  actions: {
    async getCartAction (context) {
      const { data: { list } } = await getCartList()
      list.forEach(item => { item.isChecked = true })
      context.commit('setCartList', list)
    },
    async setCartAction (context, { newNum, goodsId, goodsNum, goodsSkuId }) {
      // 更新vuex数据
      const obj = context.state.cartList.find(item => item.goods_id === goodsId)
      context.commit('setCart', { obj, newNum })
      // 更新后端
      await updetaCart({
        goodsId,
        goodsSkuId,
        goodsNum: newNum
      })
    },
    // 删除商品
    async delCartPro (context) {
      // 被选中的商品的id数组
      const selectList = context.getters.selCartList.map(item => item.id)
      if (selectList.length === 0) return
      const res = await delCart(selectList)
      console.log(res)
      // context.actions.getCartAction()
      context.dispatch('getCartAction')
      console.log('dd')
    }
  },
  getters: {
    countTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 找到被选中的
    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    selPrice (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods_num * item.goods.goods_price_min, 0)
    },
    checkAllSelect (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
